package hung.vnptthanhhoa.util;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;

public class SyncFood extends IntentService {
	JSONParser jsonParser;
	DBController controller;
	DBCooking dbCooking;
	final String urlGetSync = "http://10.41.23.115/getSync.php";
	final String urlGetSyncLMA = "http://10.41.23.115/getSyncLoaiMonAn.php";

	public SyncFood() {
		super("SyncFood");
		jsonParser = new JSONParser();
		controller = new DBController(this);
		dbCooking = new DBCooking(this);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		// Dong bo loai mon an
		JSONObject jsonLoaiMonAn = jsonParser.getJSONFromUrl(urlGetSyncLMA);

		try {
			JSONArray jsonArray = jsonLoaiMonAn.getJSONArray("post");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject e = jsonArray.getJSONObject(i);
				if (dbCooking.insertLoaiMonAn(e)) {
					DefaultHttpClient httpClient = new DefaultHttpClient();
					String urlUpdateSync = "http://10.41.23.115/updateSyncLMA.php?id="
							+ e.getInt("id");
					HttpPost httpPost = new HttpPost(urlUpdateSync);
					HttpResponse httpResponse = httpClient.execute(httpPost);
				} else
					Log.e("Loi", "Loi dong bo loai mon an");
			}
		} catch (Exception e) {

		}

		// Dong bo mon an
		JSONObject json = jsonParser.getJSONFromUrl(urlGetSync);
		try {
			JSONArray jsonArray = json.getJSONArray("post");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject e = jsonArray.getJSONObject(i);
				if (controller.insertMonAn(e)) {
					DefaultHttpClient httpClient = new DefaultHttpClient();
					String urlUpdateSync = "http://10.41.23.115/updateSync.php?id="
							+ e.getInt("id");
					HttpPost httpPost = new HttpPost(urlUpdateSync);
					HttpResponse httpResponse = httpClient.execute(httpPost);
				} else
					Log.e("Loi", "Loi dong bo mon an");
			}
		} catch (Exception e) {
		}
		// controller.deleteAll();
		// controller.getArrayListByGroupId(1);

		// Cursor cursor =
		// controller.getFoodByGroupId(1);Log.e("f",String.valueOf(cursor.getCount()));
		// if (cursor.moveToFirst()) {
		// do {
		// Log.e("cursor",cursor.getString(cursor.getColumnIndex("id"))+" "+
		// cursor.getString(cursor.getColumnIndex("group_id"))+" "+cursor.getString(cursor.getColumnIndex("name"))+" "+cursor.getString(cursor.getColumnIndex("id_sync")));
		// } while (cursor.moveToNext());
		// }

	}
}
